package com.webdiy.hr.impl;

import com.sys.plat.service.base.BaseServiceImpl;
import com.sys.plat.util.StoreData;
import com.sys.plat.web.core.ActionContext;
import com.sys.tool.HttpClientTool;
import com.sys.tool.MailTool;
import com.sys.tool.StringTool;
import com.webdiy.dao.model.HrConfig;
import com.webdiy.dao.model.HrInfo;
import com.webdiy.hr.iface.SendEmailSerice;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 2010-2-19
 * Time: 22:54:50
 * To change this template use File | Settings | File Templates.
 */
public class SendEmailSericeImpl extends BaseServiceImpl implements SendEmailSerice {


    public void sendEmail(String hcId) {
        HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, hcId);
        List<HrInfo> hiList = dao.listByHql("FROM HrInfo WHERE hrConfig = ? AND send = '1' AND finish = '1' AND mail is not null", hc.getId());
        for (HrInfo hrInfo : hiList) {
            String[] mails = hrInfo.getMail().split(",");
            for (String mail : mails) {
                String job = hc.getCoverLetter();
                job = job.replace("${formName}", "女士（先生）");
                job = job.replace("${jobName}", hrInfo.getJobName());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                job = job.replace("${newDate}", sdf.format(new Date()));
                try {
                    MailTool mt = new MailTool(hc.getSendMail(), hc.getMailPwd(), hc.getSmtp());
                    mt.post(mail, "应聘【" + hrInfo.getJobName() + "】职位。工作3年，带过项目", job);
                } catch (Exception e) {
                    log.error("邮件发送失败：名称 = " + hrInfo.getJobName() + " ; ID = " + hrInfo.getId() + " ; MAIL = " + hrInfo.getMail());
                }

                hrInfo.setFinish("2");
                dao.saveOrUpdateObject(hrInfo);
            }
        }
    }

    


    public boolean loginWeb(String hcId) {
        HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, hcId);
        if(hc.getHrWebName().equals("智联招聘")) {
            return loginZhaoPinWeb(hc.getWebName(), hc.getWebPassWord());
        }
        return false;
    }
    private boolean loginZhaoPinWeb(String name, String pwd) {
        HttpClientTool hct = new HttpClientTool();
        for (int i = 0; i < 10; i++) {
            hct.addHeader("Referer", "http://my.zhaopin.com/loginmgr/login.asp");
            hct.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0)");
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("int_count", "999"));
            list.add(new BasicNameValuePair("bkurl", ""));
            list.add(new BasicNameValuePair("loginname", name));
            list.add(new BasicNameValuePair("password", pwd));
            String html = hct.post("http://my.zhaopin.com/loginmgr/loginproc.asp", list);
            if (html.indexOf("用户登录_简历中心_智联招聘") > 0) {
                ActionContext.getRequest().getSession().setAttribute("zhaopin_HttpClient", hct);
                return true;
            }
            log.warn("尝试登录第" + (i + 1) + "次结束");
        }
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }



    public StoreData getJianLi(String hrWebName) {
         if(hrWebName.equals("智联招聘")) {
             return getZhaoPinJianLi();
         }
        return new StoreData();
    }

    public StoreData getQiuZhiXin(String hrWebName) {
        if(hrWebName.equals("智联招聘")) {
             return getZhaoPinQZX();
         }
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * 获得www.zhaopin.com简历信息
     * @return
     */
    private StoreData getZhaoPinJianLi() {
        HttpClientTool hct = (HttpClientTool) ActionContext.getRequest().getSession().getAttribute("zhaopin_HttpClient");
        if (hct == null) {
            return new StoreData();
        }

        String JlHtml = "";
        boolean jlb = true;
        while (jlb) {
            hct.setUrl("http://my.zhaopin.com/myzhaopin/resume_list.asp");
            JlHtml = hct.getInnerHTML();
            if (JlHtml.indexOf("简历管理_我的智联_智联招聘") > 0) {
                jlb =false;
            }
        }
        StringTool st = new StringTool();
        st.setPattern("<a(.*?)editName.asp\\?ext_id=(.*?)&(.*?)>(.*?)</a>");
        st.setMatcher(JlHtml);
        log.warn(st.isFind());
        String[] ids = st.getValues(2);
        String[] names = st.getValues(4);

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        for (int i = 0; i < ids.length; i++) {
            Map map = new HashMap();
            String id = ids[i];
            String name = names[i];
            map.put("id", id);
            map.put("name", name);
            list.add(map);
        }
        StoreData sd = new StoreData();
        sd.setResults(list);
        return sd;
    }


    private StoreData getZhaoPinQZX() {
        HttpClientTool hct = (HttpClientTool) ActionContext.getRequest().getSession().getAttribute("zhaopin_HttpClient");
        if (hct == null) {
            return new StoreData();
        }

        String JlHtml = "";
        boolean jlb = true;
        while (jlb) {
            hct.setUrl("http://my.zhaopin.com/myzhaopin/job_letter.asp");
            JlHtml = hct.getInnerHTML();
            if (JlHtml.indexOf("求职信_我的智联_智联招聘") > 0) {
                jlb =false;
            }
        }

        StringTool st = new StringTool();
        st.setPattern("<[a|A]([^>]*?)job_letter_edit.asp\\?var_id=([^>]*?)&([^>]*?)>([^修]*?)</[a|A]>");
        st.setMatcher(JlHtml);
        String[] ids = st.getValues(2);
        String[] names = st.getValues(4);

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        for (int i = 0; i < ids.length; i++) {
            Map map = new HashMap();
            String id = ids[i];
            String name = names[i];
            map.put("id", id);
            map.put("name", name);
            list.add(map);
        }
        StoreData sd = new StoreData();
        sd.setResults(list);
        return sd;
    }


    public void sendWebJob(String hcId) {
        HrConfig hc = (HrConfig) dao.getObject(HrConfig.class, hcId);
        if (hc.getWebName().equals("智联招聘")) {

        }
    }

    private void sendWebJobZhaoPing(HrConfig hc) {
        
        HttpClientTool hct = (HttpClientTool) ActionContext.getRequest().getSession().getAttribute("zhaopin_HttpClient");

        if (hct == null) {
            return;
        }

        List<HrInfo> list = dao.listByHql("FROM HrInfo WHERE hrConfig = ? AND send = '4' AND finish = '1' ", hc.getId());

        ArrayList<String> jobId = new ArrayList<String>();
        String jobIdTemp = "";
        int count = 0;
        for (HrInfo hrInfo : list) {
            jobIdTemp = jobIdTemp + hrInfo.getJobId() + ",";
            count++;
            if(count == 4){
                count = 0;
                jobId.add(jobIdTemp.substring(0, jobIdTemp.length()));
                jobIdTemp = "";
            }
        }

        for (String s : jobId) {
            
        }
        
    }

}
